package jeff.plugin.mybatis.util;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

/**
 * 处理XML的一些工具方法
 * 
 * @author Jeff
 *
 */
public class XMLUtils {

	public static Document toDocument(String xml, boolean namespaceAware)
			throws Exception {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setNamespaceAware(namespaceAware);
		DocumentBuilder builder = factory.newDocumentBuilder();

		StringReader sr = new StringReader(xml);
		InputSource is = new InputSource(sr);
		Document doc = builder.parse(is);
		return doc;
	}

	public static Document toDocument(String xml) throws Exception {
		return toDocument(xml, false);
	}

	public static String toString(Document document) throws Exception {
		DOMSource domSource = new DOMSource(document);
		StringWriter writer = new StringWriter();
		StreamResult result = new StreamResult(writer);
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer transformer = tf.newTransformer();
		transformer.transform(domSource, result);
		transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
		transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "yes");
		return writer.toString();
	}
	
	public static NodeList xpathToNodeList(Document document, String path) throws Exception{
		XPathFactory xFactory = XPathFactory.newInstance();
		XPath xpath = xFactory.newXPath();
		XPathExpression expr = xpath.compile(path);
		NodeList result = (NodeList)expr.evaluate(document, XPathConstants.NODESET);
		return result;
	}
	
	public static String xpathToString(Document document, String path)throws Exception{
		XPathFactory xFactory = XPathFactory.newInstance();
		XPath xpath = xFactory.newXPath();
		XPathExpression expr = xpath.compile(path);
		String result = (String)expr.evaluate(document, XPathConstants.STRING);
		return result;
	}

}
